package com.bookocean.controller;

import com.bookocean.application.common.Result;
import com.bookocean.application.service.BookApplicationService;
import com.bookocean.controller.dto.BookDto;
import com.bookocean.controller.dto.BookQuoteDto;
import com.bookocean.domain.utils.UserContextHolder;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 书籍控制器
 *
 * @author BookOcean
 * @since 2024-01-01
 */
@RestController
@RequestMapping("/book")
@RequiredArgsConstructor
public class BookController {

    private final BookApplicationService bookApplicationService;

    /**
     * 根据书名查询书籍信息
     */
    @PostMapping("/getBookInfoByName")
    public Result<BookDto> getBookInfoByName(@Valid @RequestBody BookDto bookDto) {
        BookDto bookInfo = bookApplicationService.getBookInfoByName(bookDto.getTitle());
        return Result.success(bookInfo);
    }

    /**
     * 根据书名模糊搜索书籍列表
     */
    @PostMapping("/searchBooksByName")
    public Result<List<BookDto>> searchBooksByName(@Valid @RequestBody BookDto bookDto) {
        List<BookDto> bookList = bookApplicationService.searchBooksByName(bookDto.getTitle());
        return Result.success(bookList);
    }


    /**
     * 存储书籍信息
     */
    @PostMapping("/saveBookInfo")
    public Result<BookDto> saveBookInfo(@Valid @RequestBody BookDto bookDto) {
        BookDto bookInfo = bookApplicationService.saveBookInfo(bookDto);
        return Result.success(bookInfo);
    }

    /**
     * 根据书籍id查询书籍信息（增强版，包含统计数据和用户交互状态）
     */
    @PostMapping("/getBookById")
    public Result<BookDto> getBookById(@Valid @RequestBody BookDto bookDto) {
        // 获取当前用户ID（可能为null，表示未登录用户）
        Long currentUserId = UserContextHolder.getUserId();

        // 使用增强版接口获取书籍信息
        BookDto bookInfo = bookApplicationService.getEnhancedBookById(bookDto.getBookId(), currentUserId);
        return Result.success(bookInfo);
    }

    /**
     * 保存书摘信息
     */
    @PostMapping("/saveQuoteInfo")
    public Result<BookQuoteDto> saveQuoteInfo(@Valid @RequestBody BookQuoteDto bookQuoteDto) {
        BookQuoteDto bookInfo = bookApplicationService.saveQuoteInfo(bookQuoteDto);
        return Result.success(bookInfo);
    }

    /**
     * 获取我的书摘列表
     */
    @GetMapping("/getUserQuotes")
    public Result<List<BookQuoteDto>> getMyQuotes(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String userId) {
        // 如果没有传入userId或userId无效，则使用当前登录用户的ID
        Long currentUserId;
        currentUserId = UserContextHolder.getUserId();
        List<BookQuoteDto> quotes = bookApplicationService.getUserQuotes(page, pageSize, currentUserId);
        return Result.success(quotes);
    }

}
